<template>
  <!-- 退费 -->
  <section>
    <div style="border-bottom:1px solid #eee;padding-bottom:10px;">
      <el-page-header @back="goBack" content="账单详情"></el-page-header>
    </div>
    <br />
    <div class="visit_detail_box">
      <div class="userinfo p-sm">
        <p>
          <img v-if="detail.head!=''" :src="detail.head | imageUrl" class="patient_img" alt />
          <img v-else src="/img/unknown-avatar.4f0c79ac.png" class="patient_img" alt />
        </p>
        <p>
          <span style="font-size: 20px; margin-right: 20px; vertical-align: middle;">{{detail.name}}</span>
          <i class="glyphicon glyphicon-earphone" style="vertical-align: middle; font-size: 18px;"></i>
        </p>
        <div class="user-field">
          <span>挂账：</span>
          <label
            style="color:#f70c0c;"
          >￥{{detail.chargeToTheRoom?detail.chargeToTheRoom:0 | changeMoneyToTwo}}</label>
          <!-- {{detail.archivesCode}} -->
        </div>
        <div class="user-field">
          <span>性别：</span>
          {{detail.sex | toSex}}
        </div>
        <div class="user-field">
          <span>年龄：</span>
          <!-- <label v-if="detail.age>7">{{detail.age}}岁</label>
          <label v-if="detail.age<7">{{detail.age}}岁{{detail.sdfMonth}}月{{detail.sdfDay}}天</label>-->
          <label v-if="detail.age>17">{{detail.age}}</label>
          <label v-else>{{detail.birthday|toTimeContrast}}</label>
        </div>
        <!-- <div class="user-field">
        <span>婚姻状况：</span>
        {{detail.age}}岁
        </div>-->
        <div class="user-field">
          <span>门诊号：</span>
          <span style="color: red;">{{detail.archivesCode}}</span>
        </div>
        <div class="user-field">
          <span>就诊日期：</span>
          <span>{{detail.visitTime | changeTime}}</span>
        </div>
      </div>
      <div class="user-content p-sm">
        <el-row style="margin:10px 0px;display:inline-block;width:100%;">
          <el-col :span="6">
            <label style="font-size:16px;">{{isReturn?"退费项目":'收费信息'}}</label>
          </el-col>
          <el-col style="height:10px;" :span="6"></el-col>
          <el-col style="height:10px;" :span="6"></el-col>
          <el-col style="height:10px;" :span="6">
            <!-- <el-button @click="opReturn()" style="float:right;">{{return_label}}</el-button> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <table class="table-box">
              <thead>
                <tr>
                  <th v-if="isReturn">
                    <el-checkbox
                      :indeterminate="isIndeterminate"
                      v-model="checkAll"
                      :disabled="isAllReturn"
                      @change="handleCheckAllChange"
                    ></el-checkbox>
                  </th>
                  <th>收费名称</th>
                  <th>原价</th>
                  <th>数量</th>
                  <!-- <th>单位</th> -->
                  <th v-if="!isReturn">优惠金额</th>
                  <th v-if="!isReturn">优惠后总价</th>
                  <th v-if="isReturn">折扣</th>
                  <th v-if="isReturn">折扣金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in itemList" :key="index">
                  <td v-if="isReturn" class="return-item_td">
                    <el-checkbox-group
                      v-model="checkedAdmin"
                      @change="handleCheckedCitiesChange($event,item.orderItemId,item.realityMoney)"
                    >
                      <el-checkbox
                        :label="item.orderItemId"
                        :disabled="isAllReturn"
                        :key="item.orderItemId"
                      ></el-checkbox>
                    </el-checkbox-group>
                  </td>
                  <td>{{item.sourceName}}</td>
                  <td>￥{{item.oneMoney}}</td>
                  <td>{{item.frequency}}</td>
                  <!-- <td>
                    <label v-if="item.cureDetailDTO"> {{item.cureDetailDTO.unit | changeAssist(dwList)}}</label>
                  </td>-->
                  <td>
                    <el-input
                      disabled
                      v-if="isReturn"
                      @blur="changeDis(item)"
                      v-model="item.discount"
                    >
                      <template slot="append">%</template>
                    </el-input>
                    <span v-if="!isReturn">￥{{item.discountMoney}}元</span>
                  </td>
                  <td>
                    <el-input disabled v-if="isReturn" v-model="item.realityMoney">
                      <template slot="prepend">￥</template>
                    </el-input>
                    <span v-if="!isReturn">{{item.realityMoney}}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>费用合计：</label>
            <span>￥{{detail.realAmount | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row v-if="disAmount!='' && disAmount!=0" class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>折扣金额：</label>
            <span>￥{{disAmount | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row v-for="(item,index) in billPayways" :key="index" class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>{{item.source | changeSourceName}}：</label>
            <span>￥{{item.payMoney | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>实收费用：</label>
            <span>￥{{detail.realAmount-disAmount-jmTotal | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <!-- <el-row class="money_box">
        <el-col class="other" :span="18"></el-col>
        <el-col class="money" :span="6">
          <label>合计积分：</label>
          <span>{{integralNum}}</span>
        </el-col>
        </el-row>-->
        <el-row v-if="isReturn" style="margin-top:20px;">
          <el-button
            style="float:right;"
            :disabled="checkedAdmin.length>0?false:true"
            @click="openDetail()"
          >退费</el-button>
        </el-row>
        <el-row style="margin-top:20px;">
          <el-button style="float:right;" @click="onPrint()">打印</el-button>
        </el-row>
      </div>
      <edit
        v-model="dialogEdit"
        v-if="dialogEdit"
        :total="detail.realAmount-disAmount-jmTotal"
        :orderItem="checkedAdmin"
        :orderId="orderId"
      ></edit>
    </div>
    <iframe
      v-show="showOrder"
      frameborder="0"
      height="0px"
      width="0px"
      ref="iframe"
      src="/print/charge.html"
    ></iframe>
  </section>
</template>
<script>
export default {
  name: "chargeDetail",
  data() {
    return {
      dialogRecord: false,
      dialogEdit: false,
      detail: "",
      checkedAdmin: [],
      checkAll: [],
      isIndeterminate: true,
      itemList: [],
      reductionMoney: 0,
      return_label: "退费",
      returnMoney: 0,
      total: 0,
      jmTotal:0,
      totalMoney: 0, //总金额
      billPayways: [],
      dwList: [],
      disAmount: 0,
      integralNum: 0,
      doctorId: 0,
      deptId: 0,
      jfUse: "",
      orderId: "",
      showOrder: false,
      iframeContent: {},
      btnLoading: false,
      isReturn: true,
      payDetail:'',//支付订单信息
      isAllReturn: false //是否可以选择性退款
    };
  },
  created() {
    this.getIntegralRuleById();
    let type = this.$route.query.type;
    if (type) this.isReturn = false;
  },
  mounted() {
    let th = this;
    th.getBasic();
    th.findUsUserById();
    th.getItemDetail();
    th.orderId = th.jieMi(th.$route.query.orderId);
  },
  methods: {
    findUsUserById() {
      let th = this;
      th.showLoading();
      let uid = th.jieMi(th.$route.query.patientId);
      th.$api.getThePatientLibraryById({ patientId: uid, hpId: th.adminUser.hpId })
        .then(res => {
          if (res.executed) {
            th.showLoading(false);
            let details=res.thePatientLibraryDetail;
            th.detail ={...details,...th.detail} ;
            th.active = true;
            th.ispersonal = false;
          }
        });
    },
    getItemDetail() {
      let th = this;
      let id = th.jieMi(th.$route.query.orderId);
      th.$api.getOrderItem({ orderId: id }).then(res => {
        if (res.executed) {
          let item = res.dataBody.pageInfo.list;
          let list = [];
          let _check = [];
          let total = 0;
          let info= res.dataBody;
          let details={
            deptName:info.deptName,
            doctorName:info.doctorName,
            memberName:info.payMemberName,
            realAmount:info.realAmount,
            visitTime:info.visitTime
          }
          th.detail={...details,...th.detail}
          th.billPayways = info.billPayways; //支付方式
          let billList = info.billPayways;
          let isAllReturn = false;
          let _receivedMoney=0
          for (let i = 0; i < billList.length; i++) {
            if (
              billList[i].source == 7 ||
              billList[i].source == 8 ||
              billList[i].source == 9 ||
              billList[i].source == 10
            ) {
              total += billList[i].payMoney;
            }
            //判断是否有减免金额、积分抵扣等支付方式
            if (
              billList[i].source == 2 ||
              billList[i].source == 5 ||
              billList[i].source == 6 ||
              billList[i].source == 12 ||
              billList[i].source == 13
            ) {
              isAllReturn = true;
            }
            if(billList[i].source==13 || billList[i].source==17){
              _receivedMoney+=billList[i].payMoney;
            }
          }
          th.isAllReturn = isAllReturn;
          th.deptId = item[0].deptId;
          th.doctorId = item[0].doctorId;
          let disMoney=0;
          for (let i = 0; i < item.length; i++) {
            let arr = {...{ discount: 100, realityMoney: "", discountMoney: 0 },...item[i]};
            arr.realityMoney = Number(item[i].realityMoney).toFixed(2);
            // arr.discountMoney = 0;
            _check.push(item[i].orderItemId);
            // total+=Number(item[i].realityMoney)
            disMoney+=Number(arr.discountMoney);
            list.push(arr);
          }
          th.totalMoney = total.toFixed(2);
          th.total = total.toFixed(2);
          if (th.total > th.jfUse.useNum) {
            let _total = parseInt(th.total);
            //向上取整 Math.ceil(5/2)
            //向下取整  Math.floor(5/2)
            th.integralNum =  Math.ceil(_total / Number(th.jfUse.useNum)) * th.jfUse.getNum;
          } else {
            th.integralNum = 0;
          }
          th.disAmount = disMoney.toFixed(2);
          th.jmTotal=_receivedMoney.toFixed(2);
          th.checkedAdmin = _check;
          th.itemList = list;
        } else {
          th.$message.error(res.message);
        }
      });
    },
    getBasic() {
      let th = this;
      th.getCommonConfigByKey("药品剂量单位").then(res => {
        th.dwList = res;
      });
    },
    changeDis(item) {
      let th = this;
      let dis = item.discount;
      let oldMoney = Number(item.realityMoney);
      item.realityMoney = Number(
        item.totalPrice * (item.discount / 100)
      ).toFixed(2);
      item.discountMoney = Number(item.totalPrice - item.realityMoney).toFixed(
        2
      );
      th.totalMoney =
        Number(th.totalMoney) - Number(oldMoney) + Number(item.realityMoney);
      if (th.totalMoney > th.jfUse.useNum) {
        let _total = parseInt(th.totalMoney);
        th.integralNum =
          Math.ceil(_total / Number(th.jfUse.useNum)) * th.jfUse.getNum;
      } else {
        th.integralNum = 0;
      }
    },
    //获取折扣金额
    getDisMoney() {
      let th = this;
      let item = th.itemList;
      let _total = 0;
      let total = 0;
      let _disMoney = 0;
      for (let i = 0; i < item.length; i++) {
        total += Number(item[i].realityMoney);
        _total += Number(item[i].totalPrice);
        _disMoney += Number(item[i].discountMoney);
      }
      if (th.total > th.jfUse.useNum) {
        let _total = parseInt(th.total);
        //向上取整 Math.ceil(5/2)
        //向下取整  Math.floor(5/2)
        th.integralNum =
          Math.ceil(_total / Number(th.jfUse.useNum)) * th.jfUse.getNum;
      } else {
        th.integralNum = 0;
      }
      th.total = _total.toFixed(2);
      th.totalMoney = total.toFixed(2);
      th.disAmount = _disMoney.toFixed(2);
    },
    handleCheckAllChange(val) {
      let th = this;
      let checked = [];
      for (var i = 0; i < th.itemList.length; i++) {
        checked.push(th.itemList[i].orderItemId);
      }
      th.checkedAdmin = val ? checked : [];
      if (th.checkedAdmin.length == 0) {
        th.totalMoney = 0.0;
        th.total = 0.0;
        th.disAmount = 0.0;
      } else {
        th.getDisMoney();
      }
      th.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value, id, money) {
      let th = this;
      let checkedCount = value.length;
      th.checkAll = checkedCount === th.itemList.length;
      th.isIndeterminate =
        checkedCount > 0 && checkedCount < th.itemList.length;
      let bools = value.includes(id);
      let total=th.detail.realAmount;
      if (bools == true) {
        total = Number(Number(total) + Number(money)).toFixed(2);
        th.detail.realAmount= total;
      } else {
        total = Number(Number(total) - Number(money)).toFixed(2);
        th.detail.realAmount= total;
      }
    },
    openDetail() {
      this.dialogEdit = true;
    },
    getIntegralRuleById() {
      let th = this;
      th.$api
        .getIntegralRuleById({ hpId: th.adminUser.hpId, type: 1 })
        .then(res => {
          if (res.executed) {
            th.jfUse = res.integralRuleList[0];
          }
        });
    },
    goBack() {
      this.$router.go(-1);
    },
    onPrint() {
      this.showOrder = true;
      this.showLoading();
     let doctor = this.detail.doctorName;
        // 需要改打印科室名称
       let  dept = this.detail.deptName;
      let item = this.itemList;
      this.iframeContent = this.$refs.iframe.contentWindow;
      let list = [];
      let total = 0;
      item.map((it,index)=>{
        let arr = {...it};
        if (index != 0) {
          if (index % 40 == 0) {
            arr.realityMoney = Number(arr.realityMoney).toFixed(2);
            arr.show = false;
            total += Number(arr.realityMoney);
            // list.push({ show: true });
          } else {
            arr.realityMoney = Number(arr.realityMoney).toFixed(2);
            arr.show = false;
            total += Number(arr.realityMoney);
          }
        } else {
          arr.realityMoney = Number(arr.realityMoney).toFixed(2);
          arr.show = false;
          total += Number(arr.realityMoney);
        }
        list.push(arr);
      })
      let bill = this.billPayways;
      let detail={
        archivesCode:this.detail.archivesCode,
        birthday:this.detail.birthday,
        sex:this.detail.sex,
        name:this.detail.name
      }
      this.iframeContent.postMessage(
        {
          cmd: "postJson",
          params: JSON.stringify({
            detail: detail,
            list: list,
            bill: bill,
            doctor: doctor,
            dept: dept,
            logo: this.adminUser.printLogo,
            total: this.detail.realAmount,
            disAmount:this.disAmount,//折扣金额
            memberName: this.detail.memberName,
            visitTime:this.detail.visitTime?this.detail.visitTime.substring(0,10):'',
            endTime: bill[0].gmtCreate,
            hospitalName: this.adminUser.hospitalName
          })
        },
        "*"
      );
      this.showLoading(false);
    }
  },
  components: {
    edit: () => import("../_com/editReturn")
  }
};
</script>
<style lang="scss" scoped>
@import "../_css/detail.scss";
.patient_img {
  border: 1px solid #ddd;
  border-radius: 5px;
  display: inline-block;
  width: 100px;
  height: 100px;
}
.durg_title {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.money_box {
  margin-top: 10px;
  display: inline-block;
  width: 100%;
  .other {
    height: 10px;
    display: inline-block;
  }
  .money {
    text-align: right;
    padding-right: 10px;
    display: inline-block;
  }
}
.printOrder {
  display: inline-block;
  width: 100%;
}
</style>

